package tcp.filetransfer;

import handlers.FileHandler;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import tcp.request.Request;
import tcp.request.UploadRequest;

public class UploadHandler implements Runnable {

	
	private Socket uploadSocket;
	private FileHandler handler;
	
	
	
	public UploadHandler(Socket socket, FileHandler handler) {
		this.uploadSocket = socket;
		this.handler = handler;
	}
	public void run() {
		try {
			
			PrintWriter out = new PrintWriter(this.uploadSocket.getOutputStream(),true);
			BufferedReader in = new BufferedReader(new InputStreamReader(this.uploadSocket.getInputStream()));
			
			String inputLine = null;
			while((inputLine = in.readLine()) != null){
				if(inputLine.equalsIgnoreCase("HELO FTUP")){
			    	String fileName = in.readLine();
			    	out.println("OK");
			    	ArrayList<String> fileData = new ArrayList<String>();
	    			while((inputLine = in.readLine()) != null && !inputLine.equalsIgnoreCase("EOF")){
	    				fileData.add(inputLine+"\r\n");
	    			}
	    			String[] tempArray = new String[fileData.size()];
	    			handler.createFile(fileName,handler.findFile(fileName), fileData.toArray(tempArray));
	    			inputLine = null; 
			    }
			}
			
			in.close();
			out.close();
			uploadSocket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
